﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using com.dz.ct.common;
using System.Text.RegularExpressions;

namespace com.dz.ct.components.BigSite.www.jjwxc.net
{
    public class BigSiteObject:IBigSiteObject
    {
       
        /// <summary>
        /// 获取首页所有的书籍
        /// </summary>
        /// <param name="i_book_default_url"></param>
        /// <returns></returns>
        public Dictionary<string, string> CollectDefaultBookList(string i_book_default_url)
        {
            return null;
        }

        /// <summary>
        /// 收集某个地址的所有小说详情地址
        /// </summary>
        /// <param name="i_book_list_url">http://www.jjwxc.net/bookbase.php?submit=查询&s_fw=3&s_typeid=1&s_xx=3&booktype=&orderstr=4&endstr=&page=2</param>
        /// <returns>小说地址及小说名称</returns>
        public Dictionary<string, string> CollectBookList(string i_book_list_url)
        {
            i_book_list_url = i_book_list_url.Replace("submit=查询", string.Format("submit={0}", HttpUtility.UrlEncode("查询", Encoding.GetEncoding("gb2312"))));
            string t_reg = "<a[^<>]*?hrefs*=[\'\"]*(onebook\\.php\\?novelid=\\d+)[\'\"]";

            Dictionary<string, string> t_dic = null;
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_book_list_url, Encoding.GetEncoding("gb2312"));
                string t_url = string.Empty;
                if (!string.IsNullOrEmpty(t_html))
                {
                    MatchCollection t_ma = Regex.Matches(t_html, t_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_ma != null && t_ma.Count > 0)
                    {
                        t_dic = new Dictionary<string, string>();
                        foreach (Match t_mc in t_ma)
                        {
                            if (t_mc.Groups.Count > 1)
                            {

                                t_url = string.Format("http://www.jjwxc.net/{0}", t_mc.Groups[1].Value);
                              
                                if (!t_dic.ContainsKey(t_url))
                                {
                                    t_dic.Add(t_url, "不要书名");
                                }
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error("收集小说列表地址失败" + ex.ToString());
            }

            return t_dic;
        }

        /// <summary>
        /// 收集某本小说详细信息
        /// </summary>
        /// <param name="i_book_url"></param>
        /// <returns></returns>
        public BookInfo CollectBookItem(string i_book_url)
        {
            BookInfo t_book_info = new BookInfo();

            t_book_info.BookUrl = i_book_url;
            t_book_info.ChapterUrl = i_book_url;
            t_book_info.CommentUrl = i_book_url.ToLower().Replace("onebook", "comment");
            t_book_info.SiteId = (int)Consts.Site.jjwxc;

            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_book_url, Encoding.GetEncoding("gb2312"));
                if (!string.IsNullOrEmpty(t_html))
                {
          
                    Match t_mc = Regex.Match(t_html, "<img[^<>]*?srcs*=s*[\'\"s]?([^\"]*frontcover[^\"]*)[\'\"]?[^<>]*?>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_mc != null && t_mc.Groups.Count > 0)
                    {
                        t_book_info.IsExistsImage = true;
                        t_book_info.ImageUrl = t_mc.Groups[1].Value.ToString();
                    }
                    t_mc = Regex.Match(t_html, "<div[^<>]*id=[\'\"]*novelintro[\'\"]*>(.*?)</div>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_mc != null && t_mc.Groups.Count > 0)
                    {
             
                        t_book_info.Description = t_mc.Groups[1].Value.ToString();
                        t_book_info.Description = Regex.Replace(t_book_info.Description, "<br[/]*>", "q", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                        t_book_info.Description = Regex.Replace(t_book_info.Description, "<.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                        t_book_info.Description = Regex.Replace(t_book_info.Description, "q+", "<br>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                        t_book_info.Description = t_book_info.Description.Replace("本文晋江独家发表谢绝转载", "");
                    }

                    t_mc=Regex.Match(t_html,"<span>文章类型：\\s*</span>\\s*([^-]*)\\-([^-]*)\\-([^-]*)\\-([^-]*)",RegexOptions.IgnoreCase|RegexOptions.Compiled);

                    if (t_mc != null && t_mc.Groups.Count > 2)
                    {
                        t_book_info.BookCagegoryName = t_mc.Groups[2].Value.ToString();
                        t_book_info.BookSubCagegoryName = t_mc.Groups[3].Value.ToString();
                    }
                    t_mc=Regex.Match(t_html,"<span[^<>]*class=[\'\"]*bigtext[\'\"]*\\s*>\\s*<h1>(.*?)</h1>\\s*</span>.*<h2>作者：\\s*<a.*?>(.*?)</a>\\s*</h2>",RegexOptions.IgnoreCase|RegexOptions.Compiled);

                    if (t_mc != null && t_mc.Groups.Count > 1)
                    {
                        t_book_info.BookName = t_mc.Groups[1].Value.ToString();
                        t_book_info.AuthorName = t_mc.Groups[2].Value.ToString();
                    }
                    t_mc=Regex.Match(t_html,"<div[^<>]*>[\\s\\S]* 总点击数：(\\d+)[\\s\\S]*收藏数：(\\d+)",RegexOptions.IgnoreCase|RegexOptions.Compiled);
                    if (t_mc != null && t_mc.Groups.Count > 1)
                    {
                        long t_click_count = 0;
                        if (!long.TryParse(t_mc.Groups[1].Value.ToString(), out t_click_count))
                            t_click_count = 0;
                        t_book_info.Click = t_click_count;
                        long t_collect = 0;
                        if (!long.TryParse(t_mc.Groups[2].Value.ToString(), out t_collect))
                            t_collect = 0;
                        t_book_info.Collect = t_collect;
                    }
                    t_book_info.BookStatus = "情节展开";
                   

                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("收集小说详情失败" + ex.ToString());
            }
           
            return t_book_info;
        }



        /// <summary>
        /// 收集某本书的所有章节
        /// </summary>
        /// <param name="i_chapter_list_url"></param>
        /// <returns></returns>
        public List<BookChapterInfo> CollectChapterList(string i_chapter_list_url)
        {
            List<BookChapterInfo> t_list_chapter = null;
            string t_volume_name = string.Empty;
            string t_sub_html = string.Empty;
           

            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_chapter_list_url, Encoding.GetEncoding("gb2312"));
                if (!string.IsNullOrEmpty(t_html))
                {
                    t_list_chapter = new List<BookChapterInfo>();
                    string t_reg_volume = "<b[^<>]*class=[\'\"]*volumnfont[\'\"]*>(.*?)</b>";

                    MatchCollection t_ma_volume = Regex.Matches(t_html, t_reg_volume, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_ma_volume != null && t_ma_volume.Count > 0)
                    {
                        for (int index = 0; index < t_ma_volume.Count - 1; index++)
                        {
                            t_volume_name = t_ma_volume[index].Groups[1].Value.ToString();

                            t_volume_name = Regex.Replace(t_volume_name, "<a.*?>.*?</a>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                            t_sub_html = t_html.Substring(t_ma_volume[index].Index, (t_ma_volume[index + 1].Index - t_ma_volume[index].Index));

                            t_list_chapter.AddRange(ParseChapter(t_volume_name, t_sub_html));
                        }

                        t_volume_name = t_ma_volume[t_ma_volume.Count - 1].Groups[1].Value.ToString();

                        t_sub_html = t_html.Substring(t_ma_volume[t_ma_volume.Count - 1].Index);

                        t_list_chapter.AddRange(ParseChapter(t_volume_name, t_sub_html));
                    }
                    else
                    {
                        t_list_chapter.AddRange(ParseChapter("第一卷", t_html));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(string.Format("收集小说:{0},章节失败:{1}", i_chapter_list_url, ex.ToString()));
            }
            //按跟新时间排序
            //if (t_list_chapter != null && t_list_chapter.Count > 0)
            //{
            //    t_list_chapter.Sort(delegate(BookChapterInfo t_a, BookChapterInfo t_b)
            //    {
            //        if (t_a.UpdateTime > t_b.UpdateTime)
            //            return 1;
            //        else if (t_a.UpdateTime == t_b.UpdateTime)
            //            return 0;
            //        return -1;
            //    });
            //}
            return t_list_chapter;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="i_volume_name"></param>
        /// <param name="i_text"></param>
        /// <param name="i_site_book_id"></param>
        /// <returns></returns>
        private List<BookChapterInfo> ParseChapter(string i_volume_name, string i_text)
        {
            
            string t_reg_chapter = "<td>\\s*<div[^<>]*>\\s*<a[^<>]*?(href|rel)+?=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>([^<>]*)</a>\\s*(<a[^<>]*>\\s*<font[^<>]*>\\s*\\[vip\\]\\s*</font>\\s*</a>\\s*)?\\s*</div>\\s*<div[^<>]*>.*?</div>\\s*</td>\\s*<td[^<>]*>.*?</td>\\s*<td[^<>]*>\\s*\\d+\\s*</td>\\s*(<td[^<>]*>\\s*\\d+\\s*</td>)?\\s*<td[^<>]*>(\\d{4}-[\\d{2}|\\d{1}]+-[\\d{2}|\\d{1}]+\\s[\\d{2}|\\d{1}]+:[\\d{2}|\\d{1}]+:[\\d{2}|\\d{1}]+)\\s*(<span[^<>]*>[^<>]*</span>)?</td>";

            List<BookChapterInfo> t_chapter_list = new List<BookChapterInfo>();
            try
            {
                //匹配的集合
                MatchCollection t_ma = null;
       
                i_volume_name = i_volume_name.Replace("&nbsp;", "");
                i_volume_name = Regex.Replace(i_volume_name, "(\\[.*?\\])", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                //更新时间
                DateTime t_update_time;

                bool t_is_vip = false;

                t_ma = Regex.Matches(i_text, t_reg_chapter, RegexOptions.IgnoreCase | RegexOptions.Compiled);

                if (t_ma != null && t_ma.Count > 0)
                {
                    foreach (Match t_mc in t_ma)
                    {

                        t_is_vip = false;
                        if (t_mc.Groups.Count >= 5)
                        {
                            BookChapterInfo t_book_chapter_info = new BookChapterInfo();
                            t_book_chapter_info.VolumeName = i_volume_name;
                            t_book_chapter_info.Comfrom = t_mc.Groups[2].Value.ToString();
                            t_book_chapter_info.ChapterName = t_mc.Groups[3].Value.ToString();
                            t_book_chapter_info.ChapterName = Regex.Replace(t_book_chapter_info.ChapterName, "<.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                            if (!DateTime.TryParse(t_mc.Groups[5].Value.ToString(), out t_update_time))
                                t_update_time = DateTime.Now;
                            t_book_chapter_info.UpdateTime = t_update_time;

                            if (t_mc.Groups[2].Value.ToString().ToLower().IndexOf("vip") > -1)
                            {
                                t_is_vip = true;
                            }
                            t_book_chapter_info.IsVip = t_is_vip;
   
                            t_chapter_list.Add(t_book_chapter_info);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error("收录章节失败" + ex.ToString());
            }
            return t_chapter_list;
        }

        /// <summary>
        /// 收集章节内容
        /// </summary>
        /// <param name="i_chapter_content_url"></param>
        /// <returns></returns>
        public string CollectChapterContent(string i_chapter_content_url)
        {
            if (string.IsNullOrEmpty(i_chapter_content_url))
                return string.Empty;

         
            string t_reg_content = "<div[^<>]*style=[\'\"clear:both;[\'\"]*></div>(.*?)<div[^<>]*align=[\'\"]*right[\'\"]*>";
            string t_chapter_content = string.Empty;
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_chapter_content_url, Encoding.GetEncoding("gb2312"));

                if (!string.IsNullOrEmpty(t_html))
                {

                    Match t_mc_content = Regex.Match(t_html, t_reg_content, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_mc_content != null && t_mc_content.Groups.Count > 0)
                    {
                        t_chapter_content = t_mc_content.Groups[1].Value.ToString();

                        t_chapter_content = Regex.Replace(t_chapter_content, "<font.*?>.*?</font>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                        t_chapter_content = Regex.Replace(t_chapter_content, "<div.*?>.*?</div>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                       
                        t_chapter_content = string.Format("document.write('{0}');", t_chapter_content);
                    }
                }

                return t_chapter_content;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取章节内容失败" + ex.ToString());
                return string.Empty;
            }
        }



        private string ParseContent(string i_conent)
        {
            if (string.IsNullOrEmpty(i_conent))
                return string.Empty;

            //替换掉所有的Html标记
            string t_conent = Regex.Replace(i_conent, "<[^\u4e00-\u9fa5]>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled).Trim();

            if (t_conent.Length > 250)
                return i_conent;
            return string.Empty;
        }

        /// <summary>
        /// 收集小说评论
        /// </summary>
        /// <param name="i_comment_url"></param>
        /// <returns></returns>
        public List<string> CollectReview(string i_comment_url)
        {
            List<string> t_comment_list = new List<string>();
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_comment_url, Encoding.GetEncoding("gb2312"));

                if (!string.IsNullOrEmpty(t_html))
                {
                    MatchCollection t_ma = Regex.Matches(t_html, "<div[^<>]*class=[\'\"]*readbody[\'\"]*>(.*?)</div>", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                    if (t_ma != null && t_ma.Count > 0)
                    {

                        foreach (Match t_mc_review in t_ma)
                        {
                            string t_content = t_mc_review.Groups[1].Value.ToString();
                            t_content = Regex.Replace(t_content, "<.*?>.*?<.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                            t_content = Regex.Replace(t_content, "<.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                            t_content = Regex.Replace(t_content, "此评论发自晋江手机站(wap.jjwxc.net)", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                            t_content = Regex.Replace(t_content, "晋江文学城", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                            t_content = Regex.Replace(t_content, "[a-zA-Z0-9]", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                            if (string.IsNullOrEmpty(t_content) || t_content.Length < 10)
                                continue;
                            t_comment_list.Add(t_content);
                        }
                    }
                }

                return t_comment_list;

            }
            catch (Exception ex)
            {
                LogHelper.Error("获取评论失败" + ex.ToString());
                return null;
            }
        }
    }
}
